<template>
    <div class="page">
        <a-form class="form">
            <a-input class="form-item" v-model:value="tableQuery.keyWord" placeholder="关键词搜索"></a-input>
            <a-button class="form-btn" @click="getRoleList" type="primary">查询</a-button>
        </a-form>

        <div class="page_content flex-column">
            <div class="table_tool mar-b10">
                <lo-button size="small" type="primary" color="success" @click="editRoleFn('open')">+新增角色</lo-button>
            </div>
            <div class="flex-1">
                <table-container v-slot="{containerHeight}">
                    <lo-table
                        :columns="tableColmun"
                        :dataSource="tableData"
                        :height="containerHeight">
                        <template #bodyCell="{column, record}">
                            <template v-if="column.dataIndex == 'roleName'">
                                <p>
                                    <span>{{record.roleName}}</span>
                                    <i @click="editRoleFn('open', record)" style="font-weight: bold;margin-left: 5px;color: green;" class="icon-edit1 pointer"></i>
                                </p>
                            </template>
                            <template v-if="column.dataIndex == 'op'">
                                <lo-button @click="syncRolePower(record)" class="mar-r10"  size="small" color="primary">同步权限</lo-button>
                                <lo-button @click="editRolePowerFn('open', record)" class="mar-r10"  size="small" color="primary">权限编辑</lo-button>
                                <lo-button @click="deleteRoleItem(record)" size="small" color="danger">删除</lo-button>
                            </template>
                        </template>
                    </lo-table>
                </table-container>
            </div>
        </div>
        <lo-modal
            title="新增/修改角色"
            width="500px"
            ref="editRoleRef" @confirm="editRoleFn('confirm')">
            <div>
                <a-form :label-col="{style: { width: '100px' }}">
                    <a-form-item label="角色名称：">
                        <a-input v-model:value="roleItem.roleName" placeholder="角色名称" />
                    </a-form-item>
                </a-form>
            </div>
        </lo-modal>
        <lo-modal
            title="权限编辑"
            width="500px"
            ref="editRolePowerRef" @confirm="editRolePowerFn('confirm')">
            <div>
                <Tree
                    @check="checkFn"
                    v-model:checkedKeys="checkedPerIds"
                    checkable :selectable="false"
                    :tree-data="treeData"></Tree>
            </div>
        </lo-modal>
    </div>
</template>

<script lang="jsx" setup>
    import { ref, onMounted, onActivated } from 'vue'
    import { getSysRoles, getUserSysPers, editRolePer, editSysRole, getSysPers, syncSysRolePer} from '@/api/system'
    import { Tree } from 'ant-design-vue'

    onMounted(() => {
        getRoleList()

    })
    // **************列表***************
    const tableQuery = ref({
        keyWord: ''
    })
    const tableColmun = ref([
        { title: '序号', type: 'index' },
        { title: '角色名称', dataIndex: 'roleName' },
        { title: '操作', dataIndex: 'op', align: 'center', width: '300px' },
    ])
    const tableData = ref([])
    function getRoleList() {
        getSysRoles({
            keyWord: tableQuery.value.keyWord
        }).then(res => {
            tableData.value = res.data
        })
    }

    // ************编辑*******************
    const editRoleRef = ref(null)
    const roleItem = ref({
        id: '',
        roleName: ''
    })
    function editRoleFn(type, row) {
        if(type == 'open') {
            editRoleRef.value.open()
            roleItem.value.roleName = row && row.roleName || ''
            roleItem.value.id = row && row.id || ''
        } else if(type == 'cancel') {
            editRoleRef.value.close()
        } else if(type == 'confirm') {
            editSysRole({
                id: roleItem.value.id,
                roleName: roleItem.value.roleName
            }).then(res => {
                $global.message.success(res.msg)
                getRoleList()
                editRoleFn('cancel')
            })
        }
    }
    function deleteRoleItem(item) {
        $global.modal.confirm('是否删除？').then(() => {
            editSysRole({
                id: item.id,
                delStatus: '01'
            }).then(res => {
                $global.message.success(res.msg)
                getRoleList()
            })
        })
    }
    // **********角色权限*******************
    const editRolePowerRef = ref(null)
    const treeData = ref([])
    const checkedPerIds = ref([]) //选中的ids
    const halfCheckedPerIds = ref([]) //父级半勾选节点
    let allPerList = [] //平铺后的所有权限（不是权限树）
    let actRoleItem = {}
    async function editRolePowerFn(type, row) {
        if(type == 'open') { //打开并回填
            editRolePowerRef.value.open()
            halfCheckedPerIds.value = []
            checkedPerIds.value = []
            actRoleItem = row

            // 获取子权限并转成一级数组
            let childPerRes = await getUserSysPers({
                // menuFlag: '00',
                sysRoleId: row.id
            })
            const getChlildPer = (item) => {
                if(item.subs && item.subs.length) {
                    halfCheckedPerIds.value.push(item.perId)
                    item.subs.forEach(getChlildPer)
                } else {
                    checkedPerIds.value.push(item.perId)
                }
            }
            childPerRes.data.forEach(getChlildPer)

            // 获取全权限树并标记是否选中
            let allPerRes = await getUserSysPers({
                // menuFlag: '00'
            })
            let parentArr = allPerRes.data
            const setChilren = (item) => {
                item.title = item.perName
                item.key = item.perId
                // 平铺权限树，遍历是否为节点用的
                let newItem = JSON.parse(JSON.stringify(item))
                delete newItem.subs
                allPerList.push(newItem)

                if(item.subs && item.subs.length) {
                    item.children = item.subs
                    item.children.forEach(i => {
                        setChilren(i)
                    })
                }
            }
            parentArr.forEach(setChilren)
            console.log(parentArr);
            treeData.value = parentArr

            console.log(treeData.value);
            console.log(checkedPerIds.value);
            // console.log(allPerList, checkedPerIds.value);
        } else if(type == 'confirm') { //确定
            console.log(checkedPerIds.value);
            let ids = []
            let nodes = []
            let perIds = [...halfCheckedPerIds.value, ...checkedPerIds.value]
            perIds.forEach(perId => {
                // perId是0开头的一般是nodes父级节点，过滤掉，节点perid只需要传最子节点perId
                if(('' + perId)[0] != '0') {
                    let item = allPerList.find(i => i.perId == perId)
                    if(item.isNode) {
                        nodes.push(item.perId)
                    } else {
                        ids.push(item.perId)
                    }
                }
            })
            editRolePer({
                // menuFlag: '00',
                perIds: ids.join(','),
                nodeIds: nodes.join(','),
                sysRoleId: actRoleItem.id
            }).then(res => {
                $global.message.success(res.msg)
                editRolePowerFn('cancel')
            })
        } else if(type == 'cancel') { //关闭
            editRolePowerRef.value.close()
            actRoleItem = {}
            treeData.value = []
        }
    }

    function checkFn(checkedKeys, e) {
        halfCheckedPerIds.value = e.halfCheckedKeys
    }
    function syncRolePower(row) {
        $global.modal.confirm('是否同步全平台该角色信息？').then(() => {
            syncSysRolePer({
                sysRoleId: row.id
            }).then(res => {
                $global.message.success(res.msg)
            })
        })
    }
</script>

<style lang="less" scoped>

</style>
